
from django.views import View
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from web.forms.wiki import WikiForm
from web.utils.tencent.cos import uploadFile
from web.utils.encrypt import uid
from web import models
class WikiView(View):
    '''
    知识库 首页
    '''
    def get(self, request, *args, **kwargs):
        datadict={}
        first_queryset=models.Wiki.objects.filter(project=request.tracer.project,parent__isnull=True,depth=1).order_by('id')[0:5]
        for item in first_queryset:
            temp={'id':item.id,'title':item.title,'child':[]}
            datadict[item.id]=temp
        second_queryset = models.Wiki.objects.filter(parent_id__in=list(datadict.keys()))
        for item in second_queryset:

            datadict[item.parent_id]['child'].append({'id':item.id,'title':item.title,'parent':item.parent_id})

        return render(request, 'manage/wiki.html',{'data':datadict.values()})

class WikiAddView(View):
    '''
    知识库 添加
    '''
    def get(self, request, *args, **kwargs):
        form=WikiForm(request=request)
        return render(request,'manage/wiki_add.html',{'form':form})

    def post(self,request,*args,**kwargs):
        form=WikiForm(request=request,data=request.POST)
        if form.is_valid():
            if form.instance.parent:
                depth=form.instance.parent.depth+1
                form.instance.depth=depth
            project=request.tracer.project
            form.instance.project=project
            form.save()
            url=reverse('web:wiki',kwargs={
                'project_id':project.id
            })
            return redirect(url)
        else:
            return render(request,'manage/wiki_add.html',{'form':form})


@method_decorator(csrf_exempt,name='dispatch')
class WikiCategoryView(View):
    '''
    知识库的目录
    '''
    def post(self,request,*args,**kwargs):
        datadict={}
        id=request.POST.get('id')
        queryset=models.Wiki.objects.filter(parent_id=id)[0:5]
        for item in queryset:
            datadict[item.id]={'id':item.id,'title':item.title,'child':[]}
        second_queryset = models.Wiki.objects.filter(parent_id__in=list(datadict.keys()))
        for item in second_queryset:
            datadict[item.parent_id]['child'].append({'id': item.id,
                                                      'title': item.title,
                                                      'parent': item.parent_id})

        return JsonResponse({'code':200,'data':list(datadict.values()),'error':''})

class WikiDetailView(View):
    def get(self,request,*args,**kwargs):
        id=request.GET.get('id')
        content=models.Wiki.objects.filter(id=id).first().content
        return JsonResponse({'code':200,'data':content,'error':''})

class WikiEditView(View):
    def get(self,request,*args,**kwargs):
        wiki_id=kwargs.get('wiki_id')
        object=models.Wiki.objects.filter(id=wiki_id).first()
        form=WikiForm(request=request,instance=object)
        return render(request,'manage/wiki_add.html',{'form':form})

    def post(self,request,*args,**kwargs):
        wiki_id = kwargs.get('wiki_id')
        object = models.Wiki.objects.filter(id=wiki_id).first()
        form = WikiForm(request=request,instance=object,data=request.POST)
        if form.is_valid():
            if form.instance.parent:
                depth=form.instance.parent.depth+1
                form.instance.depth=depth
            project=request.tracer.project
            form.instance.project=project
            form.save()
            print('修改数据成功')
            url = reverse('web:wiki', kwargs={
                'project_id': project.id
            })
            return redirect(url)
        else:
            print(form.errors)
            return render(request, 'manage/wiki_add.html', {'form': form})
class WikiDeleteView(View):
    def get(self,request,*args,**kwargs):
        wiki_id = kwargs.get('wiki_id')
        try:
            models.Wiki.objects.filter(project=request.tracer.project,id=wiki_id).delete()
            return JsonResponse({'code': 200, 'data': '删除成功', 'error': ''})
        except Exception as e:
            return JsonResponse({'code': 400, 'data': '', 'error': '删除失败'})

@method_decorator(csrf_exempt,name='dispatch')
class WikiUploadView(View):
    '''
    wiki 添加图片  markdown
    '''

    def post(self,request,*args,**kwargs):

        file_obj=request.FILES.get('editormd-image-file')
        bucket_name=request.tracer.project.bucket
        file_ext=file_obj.name.rsplit('.')[-1]
        file_name=file_obj.name.rsplit('.')[0]
        key_name=f'{uid(file_name)}.{file_ext}'
        file_url=uploadFile(name=bucket_name,file=file_obj,key=key_name)

        return JsonResponse({'success': 1, 'url': file_url, 'message': None})